class SongFav < ApplicationRecord
  belongs_to :user

  has_many :song_fav_songs
  has_many :songs, through: :song_fav_songs

  def toggle_song(song_id)
    if song_fav_songs.exists?(song_id: song_id)
      song_fav_songs.where(song_id: song_id).destroy_all
      'destroy'
    else
      if song_fav_songs.count >= 500
        oldest = song_fav_songs.order(updated_at: :asc).limit(1)[0]
        oldest.update(song_id: song_id)
      else
        song_fav_songs.create(song_id: song_id)
      end
      'create'
    end
  end
end
